<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.type"
        :placeholder="$t('table.type')"
        style="width:220px; margin-right: 10px;"
        class="filter-item"
        clearable
        filterable
      >
        <el-option
          v-for="item in typeOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >{{ $t('table.search') }}</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >{{ $t('table.add') }}</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      element-loading-text="加载中"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column :label="$t('table.id')" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.$index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.name')" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.qualifi')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.qualifi }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.type')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.type | typeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.cooperateTime')" width="180px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.cooperateTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.tryoutAccountInfo')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.tryoutAccountInfo }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.formalAccountInfo')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.formalAccountInfo }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.comment')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.comment }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.createTime')" width="180px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.creator')" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.creator }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.updateTime')" width="180px">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.updator')" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updator }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.actions')"
        fixed="right"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >{{ $t('table.edit') }}</el-button>
          <el-button
            v-if="scope.row.status!='deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        :current-page="listQuery.page"
        :page-sizes="[10,20,30, 50]"
        :page-size="listQuery.limit"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item :label="$t('table.name')" prop="name">
          <el-input v-model="temp.name"/>
        </el-form-item>
        <el-form-item :label="$t('table.qualifi')" prop="qualifi">
          <el-select v-model="temp.qualifi" class="filter-item" placeholder="请选择供应商资质">
            <el-option v-for="item in qualifiOptions" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.type')" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="请选择供应商类型">
            <el-option
              v-for="item in typeOptions"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.cooperateTime')" prop="cooperateTime">
          <el-date-picker v-model="temp.cooperateTime" type="datetime" placeholder="请选择合作时间"/>
        </el-form-item>
        <el-form-item :label="$t('table.tryoutAccountInfo')">
          <el-input v-model="temp.tryoutAccountInfo"/>
        </el-form-item>
        <el-form-item :label="$t('table.formalAccountInfo')">
          <el-input v-model="temp.formalAccountInfo"/>
        </el-form-item>
        <el-form-item :label="$t('table.comment')">
          <el-input :autosize="{ minRows: 2, maxRows: 4}" v-model="temp.comment" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button
          v-if="dialogStatus=='create'"
          type="primary"
          @click="createData"
        >{{ $t('table.confirm') }}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, create, update, del } from '@/api/supplier'

const typeOptions = [
  { label: '机房供应商', key: 'idc' },
  { label: '短信供应商', key: 'message' }
]

const typeKeyValue = typeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.label
  return acc
}, {})

export default {
  name: 'ComplexTable',
  filters: {
    typeFilter(type) {
      return typeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      qualifiOptions: ['S', 'A', 'B', 'C'],
      typeOptions: typeOptions,
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        comment: '',
        tryoutAccountInfo: '',
        formalAccountInfo: '',
        qualifi: '',
        type: undefined,
        cooperateTime: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        phone: [
          { required: true, message: '联系电话是必填项', trigger: 'blur' }
        ],
        linkman: [
          { required: true, message: '联系人是必填项', trigger: 'blur' }
        ],
        operatorIds: [
          { required: true, message: 'ISP类型是必填项', trigger: 'blur' }
        ],
        qualifi: [
          { required: true, message: '供应商资质是必填项', trigger: 'blur' }
        ],
        cooperateTime: [
          { required: true, message: '合作时间是必填项', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '供应商类型是必填项', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '供应商名称是必填项', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleDelete(row) {
      this.$confirm('此删除操作不可还原, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del(row).then(response => {
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        })
        .catch(() => {})
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        comment: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          create(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    }
  }
}
</script>
